import os
import sys
from tqdm import tqdm
from utils import ReadXml
import numpy as np

wu_ = r"J:\Temp\Circle\Big"
Path = wu_
SameLimitLabel = ['bridge']
LabelError = []
IdxError = []

for root, dirs, files in os.walk(Path):
    for file in tqdm(files):
        if file[-1] == "l":
            Infos = ReadXml(root + "\\" + file)
            if "_" not in file:
                continue
            TrueLabel = file.split("_")[-1][:-4]
            if TrueLabel.split("-")[0] in SameLimitLabel:
                TrueLabel = TrueLabel.replace(TrueLabel.split('-')[0], "limit")

            Result = []
            try:
                Coordinates = np.array(Infos)[:, :-1].astype(int)
            except:
                print("Maybe infos is None!Please run 'CountLabelNum' first!")
                sys.exit(0)
            Labels = np.array(Infos)[:, -1]
            if "school" in TrueLabel:
                IdxYMin = np.argmax(Coordinates[:, 1])
            else:
                IdxYMin = np.argmin(Coordinates[:, 1])
            Result.append(Labels[IdxYMin])
            Coordinates = np.delete(Coordinates, IdxYMin, 0)
            Labels = np.delete(Labels, IdxYMin, 0)
            for i in range(len(Infos) - 1):
                IdxXMin = np.argmin(Coordinates[:, 0])
                try:
                    Result.append(int(Labels[IdxXMin]))
                except:
                    IdxError.append(file)
                Coordinates = np.delete(Coordinates, IdxXMin, 0)
                Labels = np.delete(Labels, IdxXMin, 0)
            Value = 0
            for i in range(len(Result) - 1):
                Value += Result[-1 - i] * np.power(10, i)

            if TrueLabel != str(Value) and TrueLabel != Result[0] and TrueLabel != "%s%d" % (Result[0], Value) and TrueLabel != "%s-%d" % (Result[0], Value) and TrueLabel != 'RemoveLimit' + str(Value):
                LabelError.append(file)
if len(LabelError) == 0:
    print("All labels are correct")
else:
    print("%d labels error! (label sum error)" % len(LabelError))
    print(LabelError)

if len(IdxError) != 0:
    print("%d program exception! (more than one str)" % len(IdxError))
    print(IdxError)
